<template>
  <div class="main-container">
    <!-- <TableHeadSearch @searchForm="searchForm" queryCode="menuList"/> -->
    <TableHeader :can-collapsed="false">
      <template v-slot:right>
        <el-button
          type="primary"
          size="mini"
          :icon="CirclePlus"
          @click="onAddItem"
          >新增
        </el-button>
      
      </template>
    </TableHeader>
    
    <TableBody
      ref="tableBody"
      :tableLoading="tableLoading"
      :tableConfig="tableConfig"
      :tableColumns="tableColumns"
      :tableOperations="tableOperations"
      :tableData="dataList"
    >
      <template #tableConfig>
        <div
          class="flex justify-between padding"
          style="border-bottom: 1px dashed var(--el-border-color-light)"
        >
          <el-link :underline="false">表格设置</el-link>
          <div>
            <span class="margin-right">
              <el-checkbox v-model="tableConfig.border">表格边框</el-checkbox>
            </span>
            <span class="margin-right">
              <el-checkbox v-model="tableConfig.stripe">斑马纹</el-checkbox>
            </span>
            <span class="margin-right">
              <el-checkbox v-model="tableConfig.multiSelect">多选</el-checkbox>
            </span>
            <el-tooltip effect="dark" content="刷新页面" placement="top">
              <el-button
                circle
                type="success"
                :icon="RefreshIcon"
                size="mini"
                @click="doRefresh"
              />
            </el-tooltip>
            <SortableTable
              class="margin-left"
              :table-props="tableColumns"
              @update="onUpdateTable"
            />
          </div>
        </div>
      </template>
    </TableBody>
    <!-- <TableFooter
      ref="tableFooter"
      @refresh="doRefresh"
      @pageChanged="doRefresh"
    /> -->
   
  <Dialog ref="dialog"  title="编辑信息" :form-items="formItems">
      <template #content>
          <BaseForm
         class="padding-left padding-right"
          ref="baseForm"
          :form-items="formItems"
        >
            <template #prefix>
            <el-form-item :label="menuFormItem.label">
              <TreeSelector
                v-model:value="menuFormItem.value"
                placeholder="请选择上级菜单"
                :data="dataList"
                :dataFields="{
                  label: 'menuName',
                  value: 'menuOid',
                }"
              />
            </el-form-item>
          </template>
        </BaseForm>
      </template>
  </Dialog>
  </div>
</template>


<script lang="tsx" setup>
import { ElMessage } from 'element-plus';
import {computed, onMounted, reactive, ref } from "vue";

import {
  showConfirmBox,
  showErrorMessage,
  showInfoMessage,
  showSuccessMessage,
} from "@/components/types";
import { useDataTable, usePost } from "@/hooks";
import { queryMenuList,saveMenu,updateMenu,deleteMenu, } from "@/api/url";
import type { TableFooter,BaseFormType, DialogType } from "@/components/types";
import {
  Delete,
  CirclePlus,
  Refresh as RefreshIcon,
} from "@element-plus/icons";
import { arraytotree} from "@/utils/index";
const {
  handleSuccess,
  selectRows,
  dataList,
  tableConfig,
  tableLoading,
  handleSelectionChange,
} = useDataTable();
const post = usePost();
const tableFooter = ref<TableFooter>();
const dialog = ref<DialogType>();
const baseForm = ref<BaseFormType>();
const tableColumns = reactive([
  { label: "菜单图标", 
    prop: "menuIcon", 
    checked:true,
  },
  { label: "菜单名", 
    prop: "menuName", 
    checked:true,
  },
  { label: "菜单排序", 
    prop: "menuOrder", 
    checked:true,
  },
  { label: "菜单路由", 
    prop: "menuUrl", 
    checked:true,
  },
  { label: "菜单编码", 
    prop: "menuCode", 
    checked:true,
  },
  { label: "权限标识", 
    prop: "perms", 
    checked:true,
  },
  { label: "菜单类型", 
    prop: "menuType", 
    checked:true,
    width:80,
    type: "Render",
    render: (h: any, { menuType }: any) => {
      if (menuType === 0) {
        return <el-button type="text">目录</el-button>;
      }
      if (menuType === 1) {
        return <el-button type="text">菜单</el-button>;
      }
      if (menuType === 2) {
        return <el-button type="text">按钮</el-button>;
      }
      return <el-button type="text">目录</el-button>;
    },
  },

]);
const tableOperations = reactive([
  {
    text: "编辑",
    key: "edit",
    type: "primary",
    handler: (row: any) => handleEdit(row),
  },
  {
    text: "删除",
    key: "delete",
    type: "danger",
    size: "mini",
    handler: (row: any) => onDeleteItem(row),
  },
]);
const menuFormItem =  reactive({ label: "上级菜单", 
    name: "parentOid", 
    value: 0,
    hidden:true,
    selectOptions: {},
    reset() {
                this.value = 0;
            },
  });
const formItems = reactive([
  { label: "", 
    type: 'input',
    name: "menuOid", 
    hidden: true,
    value: 0,
    maxlength: 20,
    placeholder: '请输入菜单主键OID',
    reset() {
                this.value = 0;
            },
  },
  { label: "", 
    type: 'input',
    name: "versionNo", 
    value: 0,
    hidden: true,
    placeholder: '请输入版本号',
    reset() {
                this.value = 0;
            },
  },
    { label: "菜单类型", 
    type: 'radio-group',
    name: "menuType", 
    value: 1,
    radioOptions: [
        {
          label: "目录", 
          value: 0
        },
        {
          label: "菜单", 
          value: 1
        },
         {
          label: "按钮", 
          value: 2
        },
    ],
    reset() {
                this.value = 1;
            },
  },
 menuFormItem,
  { label: "菜单名", 
    type: 'input',
    name: "menuName", 
    value: '',
    maxlength: 20,
    placeholder: '请输入菜单名',
    validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = "";
            },
  },
 { label: "菜单编码", 
    type: 'input',
    name: "menuCode", 
    value: '',
    maxlength: 20,
    placeholder: '请输入菜单编码',
    validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = "";
            },
  },
  { label: "菜单图标", 
    type: 'select',
    name: "menuIcon", 
    value: '',
    selectOptions: [
      {
         label: "一级菜单", 
         value: "SettingIcon"
      },
      {
         label: "二级菜单", 
         value: "GridIcon"
      },
      
    ],
    reset() {
                this.value = "";
            },
  },
  { label: "菜单排序", 
    type: 'number',
    name: "menuOrder", 
    value: '',
    maxlength: 20,
    placeholder: '请输入菜单排序',
    validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = "";
            },
  },
  
  { label: "菜单路由", 
    type: 'input',
    name: "menuUrl", 
    value: '',
    maxlength: 20,
    placeholder: '请输入菜单路由',
    validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = "";
            },
  },
 
  { label: "权限标识", 
    type: 'input',
    name: "perms", 
    value: '',
    maxlength: 20,
    placeholder: '请输入权限标识',
    validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = "";
            },
  },


]);

function handleEdit(data: any) {
  onUpdateItem(data);
}
const onUpdateItem = (item: any) => {
  formItems.forEach((it) => {
    const propValue = item[it.name];
    it.value = propValue;
  });
  menuFormItem.value = item.parentId;
  dialog.value?.show(() => {
    if (!baseForm.value?.checkParams()) {
      return;
    }
    (dialog.value as any).loading = true;
    setTimeout(() => {
      submitForm(updateMenu,baseForm.value?.generatorParams())
      dialog.value?.close();
    }, 1000);
  });
};

function doRefresh() {
  //  tableFooter.value?.setPageSize(100);
   let params = {
    //page: tableFooter.value?.withPageInfoData(),
    page: {
      currentPage:1,
      perPage:200,
    },
  }
  queryList(queryMenuList,params);
}
function queryList(url: string, params: any) {
  post({
    url: url,
    data: params,
  })
    .then((res: any) => {
      let allMenus = arraytotree(res.resultList);
      const obj = {
        data: allMenus
      };
      handleSuccess(obj);
      // tableFooter.value?.setTotalSize(res.pageUI.total);
      tableConfig["tree"] = {rowKey:"menuOid",child:allMenus}
      handleSuccess(obj);
    //  tableFooter.value?.setTotalSize(res.pageUI.total);
     
    })
    .catch(console.log);
}

function submitForm(submitUrl: string ,params: any) {
   post({
    url: submitUrl,
    data: params,    
  })
  .then((res: any) => {
     ElMessage.success("数据提交成功！");
     doRefresh();
  })
  .catch(console.log);
}

const onAddItem = () => {
  baseForm.value?.resetParams();
  dialog.value?.show(() => {
    if (!baseForm.value?.checkParams()) {
      return;
    }
    (dialog.value as any).loading = true;
    setTimeout(() => {
      submitForm(saveMenu,baseForm.value?.generatorParams())
      dialog.value?.close();
    }, 1000);
   
  });
};

function onDeleteItem(data: any) {
    post({
      url: deleteMenu,
      data: {
        menuOid: data.menuOid,
    },
  })
  .then(() => {
    doRefresh();
    showSuccessMessage("删除成功");
  })
  .catch(console.log);
 
}


function onUpdateTable(temp: Array<TablePropsType>) {
  tableColumns.length = 0;
  tableColumns.push(...temp.filter((it: TablePropsType) => it.checked));
}

menuFormItem.selectOptions = computed(() => {
  return dataList.map((it: any) => {
    return {
      label: it.menuName,
      value: it.menuOid,
    };
  });
});
onMounted(doRefresh);
</script>
<style lang="scss" scoped>
.avatar-container {
  position: relative;
  width: 30px;
  height: 30px;
  margin: 0 auto;
  vertical-align: middle;
  .avatar {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
  .avatar-vip {
    border: 2px solid #cece1e;
  }
  .vip {
    position: absolute;
    top: 0;
    right: -9px;
    width: 15px;
    transform: rotate(60deg);
  }
}
.gender-container {
  .gender-icon {
    width: 20px;
  }
}
</style>
